package cn.huiyunche.base.service.framework.redis;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.util.StringUtils;
import redis.clients.jedis.JedisPoolConfig;

import java.util.Set;

/**
 * Redis哨兵配置.
 * <p>
 *
 * @author zhaoshb
 * @since 0.0.1
 */
@Configuration
public class RedisConfiguration {

    @Value("${spring.redis.sentinel.master}")
    private String sentinelMasterName = null;

    @Value("${spring.redis.sentinel.nodes}")
    private String hostAndPorts = null;

    @Value("${jedis.maxTotal}")
    private String maxTotal = null;

    @Value("${jedis.maxIdle}")
    private String maxIdle=null;

    @Value("${jedis.maxWaitMillis}")
    private String maxWaitMillis=null;

    @Value("${jedis.testOnBorrow}")
    private String testOnBorrow=null;


    @Bean
    public MindsJedisConnectionFactory connectionFactory() {
        Set<String> sentinelHostAndPorts = StringUtils.commaDelimitedListToSet(this.getHostAndPorts());
        RedisSentinelConfiguration sc = new RedisSentinelConfiguration(this.getSentinelMasterName(), sentinelHostAndPorts);

        JedisPoolConfig pool = new JedisPoolConfig();
        pool.setMaxTotal(Integer.valueOf(this.maxTotal));
        pool.setMaxIdle(Integer.valueOf(this.maxIdle));
        pool.setMaxWaitMillis(Integer.valueOf(this.maxWaitMillis));
        pool.setTestOnBorrow(Boolean.valueOf(this.testOnBorrow));

        return new MindsJedisConnectionFactory(sc,pool);
    }

    private String getSentinelMasterName() {
        return this.sentinelMasterName;
    }

    private String getHostAndPorts() {
        return this.hostAndPorts;
    }

}
